<template>
  <!-- <div class="app-container" @contextmenu.prevent> -->
  <div class="app-container">
    <!-- 信息内容 -->
    <div class="info-wrap">
      <div class="info-container">
        <!-- 试卷信息 -->
        <div class="paper-info">
          <div class="paper-left">
            <div class="paper-title">{{ paperInfo.title }}</div>
            <div class="paper-declare" style="margin-right: 20px">总分：{{ paperInfo.score }}分</div>
            <div class="paper-declare">时长：{{ paperInfo.time }}{{ readOnly ? '' : '分钟' }}</div>
          </div>
          <div class="paper-right">
            <!-- 剩余时间 -->
            <div class="time-remaining">
              剩余时间
              <div class="count-down">{{ formatRemainTime(remainTime) }}</div>
            </div>
          </div>

          <div v-if="readOnly">
            <div class="paper-declare" style="margin-right: 20px">得分：{{ paperInfo.userScore }}分</div>
            <!-- <div class="paper-declare">用时：{{ paperInfo.time }}分钟</div> -->
          </div>
        </div>
        <!-- 答题卡 -->
        <div class="answer-sheet">
          <div v-for="(list, name) in questionIds" :key="name" class="question-type">
            <!-- {{ name }} -->
            <!-- {{ list }} -->
            <div class="type-title" v-if="readOnly">{{ name }}型题</div>
            <div class="type-title" v-else>{{ list[name].questionType }}型题</div>
            <el-tag
              v-for="(item, index) in list"
              :key="name + index"
              :type="!readOnly ? '' : 'danger'"
              :effect="currentQuestionMark.type === name && currentQuestionMark.id === item.id ? 'dark' : item.effect"
              @mouseenter.native="changeTagType(name, index)"
              @mouseout.native="changeTagType(name, index)"
              @click.native="changeQuestionMark(name, item.questionTypeId, item.id, index)"
              >{{ index + 1 }}</el-tag
            >
          </div>
          <template v-if="!readOnly">
            <!-- 操作按钮 -->
            <div class="actions">
              <el-button type="primary" @click="submitPaper(true)">提交试卷</el-button>
            </div>
          </template>
        </div>
      </div>
    </div>

    <!-- 试题内容 -->
    <div class="question-container">
      <!-- 题目 -->
      <div class="questions">
        <question
          v-if="questionInfo"
          :question-info="updateQuestionInfo"
          :question-mark="questionIds[currentQuestionMark.type][currentQuestionMark.index]"
          :read-only="readOnly"
          @change="changeAnswer" />
      </div>

      <!-- 上/下一题 -->
      <template>
        <div v-if="questionTypes.length" class="pre-next-btns">
          <el-button
            type="primary"
            :disabled="currentQuestionMark.index === 0 && currentQuestionMark.type === questionTypes[0].type"
            @click="changeQuestion('pre', $event)"
            >上一题</el-button
          >
          <el-button
            type="primary"
            :disabled="
              currentQuestionMark.index === questionTypes[questionTypes.length - 1].questionNumber - 1 &&
              currentQuestionMark.type === questionTypes[questionTypes.length - 1].type
            "
            @click="changeQuestion('next', $event)"
            >下一题</el-button
          >
        </div>
      </template>
      <!-- 当前在做的题的标识：{{ currentQuestionMark }}<br> -->
      <!-- 当前在做的题的标识：{{ questionIds[currentQuestionMark.type][currentQuestionMark.index] }} -->
    </div>

    <!-- 考试结束弹窗 -->
    <el-dialog
      title="考试已结束"
      :visible.sync="dialogVisible"
      width="40%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false">
      <div>
        <div style="margin-bottom: 20px">您的分数是：{{ userScore }} 分</div>
        <div>考试时长：{{ duration }}</div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="backHome">返回主页</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { findQuestionInfo, getExamByUser, getExamInfoById, insertExamRecord, randomQuestion } from '@/api/testPage'
import { formatSeconds } from '@/utils'
import Question from './Question.vue'
import { removeItem } from '@/utils/storage'

const LETTER = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'] // 选项前缀
export default {
  name: 'TestPage',
  components: { Question },
  data() {
    return {
      bankIds: null,
      questionEquipmentId: null,
      remainTime: 0, // 剩余时间（秒数）
      timer: null,
      paperInfo: {}, // 试卷信息
      readOnly: false,
      questionTypes: [], // 试题类型
      questionIds: {}, // 试题数据id 及 额外标志属性
      questionInfo: null, // 当前试题数据
      currentQuestionMark: {}, // 当前在做的题的标识
      dialogVisible: false, // 考试结束提示对话框
      duration: '00:00:00', // 考试时长
      userScore: 0, // 考试得分
      examId: '', //考试id
    }
  },
  computed: {
    updateQuestionInfo() {
      return this.questionInfo
    },
  },
  watch: {},
  created() {
    // 获取传过来的参数
    const params = this.$route.params
    console.log(params, 'params')
    params.examName = this.$route.query.examName
    this.examId = params.examId
    // console.log(params.readOnly, 'readOnly')
    // 判断是否为查阅页面
    if (params.readOnly == 'true') {
      this.readOnly = true
      this.getExamedQuestion(params)
      return false
    }
    // 获取考卷所有题目id
    this.getExamQuestion(params)
    // 获取随机题目所有题目id
    this.getRandomQuestion(params)
    console.log(this.currentQuestionMark, 'currentQuestionMark')
  },
  mounted() {
    console.log(this.questionIds, 'questionIds')
    console.log(this.questionInfo, 'questionInfo')
    console.log(this.readOnly, 'readOnly')
  },

  beforeDestroy() {
    window.clearInterval(this.timer)
  },
  destroyed() {
    removeItem('questionList')
  },
  methods: {
    // 查阅考试
    async getExamedQuestion(params) {
      console.log(params.examId, 'sss')
      const res = await getExamByUser({ examId: params.examId })
      console.log(res.data, 'res.data')
      const data = {}
      res.data.questionIds.split('&').map((item) => {
        const key_value = item.split('@')
        console.log(key_value, 'key_value')
        data[key_value[0]] = {
          questionList: key_value[1].split(',').map((idItem) => {
            return { id: parseInt(idItem) }
          }),
        }
      })
      res.data.userAnswers.split('&').map((item) => {
        const key_value = item.split('@')
        key_value[1] = key_value[1].split('-')
        data[key_value[0]].questionList.map((item, index) => {
          item['answer'] = key_value[1][index]
        })
      })
      console.log('获取查阅考卷数据', res)
      console.log(data, 'data')
      this.setQuestionIds(data)
      this.setCorrect(res.data.errorQuestionIds)
      this.$set(this.paperInfo, 'title', params.examName) // 名称
      this.$set(this.paperInfo, 'score', res.data.totalScore) // 总分
      this.$set(this.paperInfo, 'userScore', res.data.logicScore) // 得分
      this.$set(this.paperInfo, 'time', res.data.duration) // 时长
      //#region
      // .then((res) => {
      //
      //   // 题目id
      //   res.data.questionIds.split('&').map((item) => {
      //     const key_value = item.split('@')
      //     data[key_value[0]] = {
      //       questionList: key_value[1].split(',').map((idItem) => {
      //         return { id: parseInt(idItem) }
      //       }),
      //     }
      //   })
      //   // 题目答案id
      //   res.data.userAnswers.split('&').map((item) => {
      //     const key_value = item.split('@')
      //     key_value[1] = key_value[1].split('-')
      //     data[key_value[0]].questionList.map((item, index) => {
      //       item['answer'] = key_value[1][index]
      //     })
      //   })
      //   console.log('获取查阅考卷数据', res)
      //   console.log(data, 'data')
      //   this.setQuestionIds(data)
      //   // this.setCorrect(res.data.errorQuestionIds)
      //   this.$set(this.paperInfo, 'title', params.examName) // 名称
      //   this.$set(this.paperInfo, 'score', res.data.totalScore) // 总分
      //   this.$set(this.paperInfo, 'userScore', res.data.logicScore) // 得分
      //   this.$set(this.paperInfo, 'time', res.data.duration) // 时长
      // })
      //#endregion
    },

    // 答题卡显示正确/错误的颜色
    setCorrect(errorQuestionIds) {
      console.log(errorQuestionIds, 'errorQuestionIds')
      // 错题的id
      errorQuestionIds = errorQuestionIds.split(',').map((item) => parseInt(item))
      console.log(this.questionIds, 'questionIds')
      for (const typeItem in this.questionIds) {
        // if (typeItem === 'B') {
        //   this.questionIds[typeItem].map((item) => {
        //     item.correct = true
        //     findQuestionInfo({
        //       questionId: item.id,
        //     }).then((res) => {
        //       console.log('试题内容', res.data)
        //       res.data.map((childItem) => {
        //         if (errorQuestionIds.includes(childItem.questionId)) {
        //           item.correct = false
        //         }
        //       })
        //     })
        //   })
        // }
        this.questionIds[typeItem].map((item) => {
          if (errorQuestionIds.includes(item.id)) {
            item.correct = false
          } else {
            item.correct = true
          }
          return item
        })
        // else {

        // }
      }
      console.log('questionIds', this.questionIds)
    },
    // 考试
    async getExamQuestion(params) {
      console.log('获取考卷所有题目id', params)
      if (params.examId === 'false') return false
      console.log('获取考卷考题: 试卷id', params.examId)
      const res = await getExamInfoById({ examId: params.examId })
      console.log('获取考卷考题数据', res)
      this.setQuestionIds(res.data)
      this.$set(this.paperInfo, 'title', params.examName)
      this.$set(this.paperInfo, 'time', res.examinationTime)
      this.$set(this.paperInfo, 'score', this.countTotalScore())
      this.setTimer(res.examinationTime) // 设置定时器
    },
    // 获取随机考题（目前是判断条件让后面的逻辑不执行）
    async getRandomQuestion(params) {
      console.log(params, 'params')
      this.bankIds = params.bankIds !== 'false' ? params.bankIds.split(',') : params.bankIds
      this.questionEquipmentId = params.questionEquipmentId !== 'false' ? params.questionEquipmentId : null
      console.log(this.bankIds, 'bandIds')
      if (this.bankIds === 'false') return false
      console.log('获取随机考题:题库id列表', this.bankIds)
      console.log('传递的参数', {
        quBankId: this.bankIds,
        level: parseInt(this.questionEquipmentId),
        questionEquipmentId: parseInt(this.questionEquipmentId),
      })
      const res = await randomQuestion({
        quBankId: this.bankIds,
        level: parseInt(this.questionEquipmentId),
        questionEquipmentId: parseInt(this.questionEquipmentId),
      })
      console.log('获取随机考题数据', res)
      this.setQuestionIds(res.data)
      this.$set(this.paperInfo, 'title', `随机试题训练-${+new Date().getTime().toString().substring(9)}`)
      console.log(`${+new Date().getTime().toString().substring(9)}`, 'TitleTime')
      this.$set(this.paperInfo, 'time', res.examinationTime)
      this.$set(this.paperInfo, 'score', this.countTotalScore())

      this.setTimer(res.examinationTime) // 设置定时器
    },

    // 设置试题id额外属性
    // 设置试题类型
    // 初始化当前题目
    setQuestionIds(IdsData) {
      console.log(IdsData, 'IdsData')
      // const typeMap = {
      //   A1: '1',
      //   X: '2',
      //   'A3/4': '3',
      //   B: '4',
      //   A2: '5',
      // }
      // console.log(IdsData, 'IdsData')

      for (const typeItem in IdsData) {
        console.log(typeItem, 'typeItem')
        //#region
        // ---------------------------------------
        // if (typeItem == 'B') {
        //   let obj = {}
        //   let arr = []
        //   IdsData[typeItem].questionList.forEach((item, index) => {
        //     if (!obj[item.childList]) {
        //       obj[item.childList] = item.childList
        //       arr.push(item)
        //     }
        //   })
        //   IdsData[typeItem].questionList = arr
        // }
        // ---------------------------------------
        //#endregion
        console.log(IdsData, 'updateIdsData')
        console.log(IdsData[typeItem].name, 'typeItem')
        const questionIds = IdsData[typeItem].questionList.map((item, index) => {
          console.log(item, 'item')
          return {
            // 题目类型
            questionType: IdsData[typeItem].name ?? typeItem,
            // questionTypeId: parseInt(typeMap[typeItem === 'A3_4' ? 'A3/4' : typeItem]),
            id: item.quParentId || item.id, // 题目的id
            questionTypeId: IdsData[typeItem].id, //题目类型的id
            childList: item.quParentId ? item.childList : null, // 题目id（不含quParentId）
            type: 'info', // 答题卡要显示的样式类型
            effect: 'light', // 答题卡要显示的样式主题
            answer: item.answer || 'N', // 答案
            correct: item.correct || null, // 是否回答正确
            score: IdsData[typeItem].score || item.score, // 本类题分数
            index,
          }
        })
        console.log(questionIds, 'questionIdV')

        if (questionIds.length) {
          this.questionTypes.push({
            type: typeItem,
            // typeId: parseInt(typeMap[typeItem]),
            score: IdsData[typeItem].score,
            questionNumber: questionIds.length,
          })
          console.log(this.questionTypes, 'questionTypes')
          this.$set(this.questionIds, typeItem, questionIds)
          console.log(this.questionIds, 'questionIds')
        }
      }
      console.log(this.questionIds, 'questionIds')
      console.log(this.questionTypes, 'questionTypes')
      // 初始化当前题目
      this.$set(this.currentQuestionMark, 'type', this.questionTypes[0].type) // 该题所属题型
      // 该题所属题型
      // this.$set(this.currentQuestionMark, 'typeId', this.questionTypes[0].typeId)

      this.$set(this.currentQuestionMark, 'id', this.questionIds[this.questionTypes[0].type][0].id) // 该题id
      this.$set(this.currentQuestionMark, 'index', 0) // 该题在所属题型内的index
      console.log(this.currentQuestionMark, 'currentQuestionMark')
      this.getQuestionInfo(this.currentQuestionMark) // 获取当前题目内容
    },

    // 计算试卷总分
    countTotalScore() {
      let total = 0
      console.log('haha', this.questionIds)
      for (const typeItem in this.questionIds) {
        // console.log(this.questionIds[typeItem])
        // if (typeItem === 'B') {
        //   total = this.questionIds[typeItem].reduce((temp, now) => {
        //     return (temp += now.childList.length * now.score)
        //   }, total)
        // }

        total = this.questionIds[typeItem].reduce((temp, now) => {
          return (temp += now.score)
        }, total)
      }
      return total
    },
    setTimer(minute) {
      // 获取传递的时间，并且转换为整型
      const [hours, minutes, seconds] = minute.split(':').map(Number)
      // console.log(hours, minutes, seconds)
      // 将总时间转换为秒数
      const totalSecond = hours * 60 * 60 + minutes * 60 + seconds
      // 设置剩余时间
      this.remainTime = totalSecond
      // 创建一个定时器
      const timer = setInterval(() => {
        // 如果剩余时间小于0，提交试卷
        if (this.remainTime <= 0) {
          this.submitPaper(false)
          clearInterval(timer)
        } else {
          // 否则就计算剩余时间小时，分钟和秒
          const hours = Math.floor(this.remainingTime / 3600)
          const minutes = Math.floor((this.remainingTime % 3600) / 60)
          const seconds = this.remainingTime % 60
          // console.log(`${hours}:${minutes}:${seconds}`)
          --this.remainTime
        }
      }, 1000)
      // console.log(minute, 'minute')
      // let curS = '' //当前秒数
      // if (sessionStorage.getItem('curTime')) {
      //   curS = parseInt(new Date().getTime() / 1000) - JSON.parse(sessionStorage.getItem('curTime'))
      // } else {
      //   // 获得当前时间的时间戳
      //   let curTime = parseInt(new Date().getTime() / 1000)
      //   console.log(curTime, 'curTime')
      //   sessionStorage.setItem('curTime', JSON.stringify(curTime))
      //   curS = 0
      // }
      // console.log(curS)
      // this.remainTime = parseInt(minute) * 60 - curS
      // this.timer = setInterval(() => {
      //   if (this.remainTime <= 0) {
      //     // 剩余时间为零，提交试卷
      //     this.submitPaper(false)
      //   } else {
      //     --this.remainTime
      //   }
      // }, 1000)
    },
    // // 设定计时器

    // 格式化剩余时间
    formatRemainTime(time) {
      return formatSeconds(time)
    },

    // 答题卡题目鼠标经过
    changeTagType(type, index) {
      if (this.questionIds[type][index].answer !== 'N') return
      if (this.questionIds[type][index].type === 'info') {
        this.$set(this.questionIds[type][index], 'type', '')
      } else if (this.questionIds[type][index].type === '') {
        this.$set(this.questionIds[type][index], 'type', 'info')
      }
    },

    // 答题卡题目被点击
    changeQuestionMark(type, typeId, id, index) {
      console.log(this.currentQuestionMark, 'currentQuestionMark')
      this.$set(this.currentQuestionMark, 'type', type)
      this.$set(this.currentQuestionMark, 'typeId', typeId)
      this.$set(this.currentQuestionMark, 'id', id)
      this.$set(this.currentQuestionMark, 'index', index)
      this.getQuestionInfo(this.currentQuestionMark) // 调用获取试题数据
    },

    // 切换题目
    changeQuestion(operator, e) {
      console.log('切换题目', operator, e)
      console.log(this.currentQuestionMark, 'currentQuestionMark')
      // 切换当前试题的标识
      let type = this.currentQuestionMark.type
      let typeId = this.currentQuestionMark.typeId
      let id = this.currentQuestionMark.id
      let index = this.currentQuestionMark.index
      console.log(type, 'type')
      console.log(this.questionIds, 'questionIdstype')
      // 1、当处于该类试题中
      if (index > 0 && index < this.questionIds[type].length - 1) {
        if (operator === 'pre') {
          index = --index
        } else {
          index = ++index
        }
        id = this.questionIds[type][index].id
      } else if (index === 0) {
        // 2、当处于该类试题中索引为0的位置
        if (operator === 'pre') {
          // 获取上一类型题的数量 及 上一类型题最后一道
          const preType = this.questionTypes[this.questionTypes.findIndex((item) => item.type === type) - 1]
          const lastIndex = this.questionIds[preType.type].length - 1
          const lastQuestion = this.questionIds[preType.type][lastIndex]
          type = preType.type
          typeId = preType.typeId
          index = lastIndex
          id = lastQuestion.id
        } else {
          index = ++index
          id = this.questionIds[type][index].id
        }
      } else if (index === this.questionIds[type].length - 1) {
        // 3、当处于该类试题中索引为最后一个的位置
        // 获取下一类型题的数量 及 下一类型题第一道
        if (operator === 'pre') {
          index = --index
          id = this.questionIds[type][index].id
        } else {
          const nextType = this.questionTypes[this.questionTypes.findIndex((item) => item.type === type) + 1]
          const firstQuestion = this.questionIds[nextType.type][0]
          type = nextType.type
          typeId = nextType.typeId
          index = 0
          id = firstQuestion.id
        }
      }
      this.$set(this.currentQuestionMark, 'type', type)
      this.$set(this.currentQuestionMark, 'typeId', typeId)
      this.$set(this.currentQuestionMark, 'id', parseInt(id))
      this.$set(this.currentQuestionMark, 'index', index)

      let target = e.target
      if (target.nodeName === 'SPAN' || target.nodeName === 'I') {
        target = e.target.parentNode
      }
      target.blur() // 让按钮失焦恢复背景颜色
      this.getQuestionInfo(this.currentQuestionMark) // 调用获取试题数据
    },

    // 获取试题内容
    getQuestionInfo(questionInfo) {
      console.log(questionInfo, 'questionInfo')
      // 在此处先进行判断看持久化存储中是否存储了
      // console.log(this.$store.getters.questionList, 'getquestionList')
      // console.log(questionInfo, 'getquestionInfo')
      findQuestionInfo({
        questionId: questionInfo.id,
      }).then((res) => {
        console.log('试题内容', res.data)
        // 初始化设置为没有保存
        res.data.isLocked = false
        // 初始化题目没有回答
        res.data.isAnswer = false
        if (res.data.answer) {
          res.data.answer.map((item, index) => {
            item.answer = `${LETTER[index]}. ${item.answer}`
          })
        } else {
          res.data[0].answer.map((item, index) => {
            item.answer = `${LETTER[index]}. ${item.answer}`
          })
        }
        this.questionInfo = res.data
        const QuestionListStore = this.$store.getters.questionList
        console.log('试题内容', res.data)
        console.log(QuestionListStore, 'QuestionListStore')
        // 判断改题目是否已经被持久化保存
        if (QuestionListStore.length > 0) {
          const index = QuestionListStore.findIndex((item) => item.questionId == questionInfo.id)
          if (index !== -1) {
            this.questionInfo.isLocked = QuestionListStore[index].isLocked
            this.questionInfo.isAnswer = QuestionListStore[index].isAnswer
            // console.log(this);
            // console.log(this.questionInfo, 'qeustionInfo')
            return
          }
        }
        console.log(this.questionInfo, 'ThisqeustionInfo')
      })
    },

    // 更新答案
    changeAnswer(info) {
      // 判断当前大的题目是否保存
      console.log('信息', info)
      // console.log(this.currentQuestionMark)
      console.log(this.questionIds, 'questionIds')
      console.log(this.currentQuestionMark.type, 'type')
      console.log(this.currentQuestionMark, 'currentQuestionMark')
      console.log(this.questionIds[this.currentQuestionMark.type][this.currentQuestionMark.index].type, '更改答案')
      // 切换答题卡状态
      this.questionIds[this.currentQuestionMark.type][this.currentQuestionMark.index].type = info.hasAnswer
        ? ''
        : 'info'
      this.questionIds[this.currentQuestionMark.type][this.currentQuestionMark.index].effect = info.hasAnswer
        ? 'dark'
        : 'light'

      // 更新答案
      this.questionIds[this.currentQuestionMark.type][this.currentQuestionMark.index].answer = info.answerId
      this.questionIds[this.currentQuestionMark.type][this.currentQuestionMark.index].correct = info.correct
    },

    // 提交试卷
    submitPaper(active) {
      console.log('主动提交: ', active)
      if (active) {
        // console.log('提交了试卷')
        this.$confirm('确认提交？', '提示', {
          showClose: false,
          cancelButtonText: '取消',
          confirmButtonText: '提交',
        })
          .then((res) => {
            console.log('提交试卷', res)
            removeItem('questionList')
            window.clearInterval(this.timer)
            this.addExamRecord()
          })
          .catch((errr) => {
            console.log(errr)
          })
      } else {
        //  在提交试卷之后清除浏览器缓存
        removeItem('questionList')
        window.clearInterval(this.timer)
        // console.log('时间到了,自动提交试卷')
        //  提交试卷
        this.addExamRecord()
      }
    },
    // 格式化考试时间
    formatPaperInfoTime(time) {
      // 格式化为秒
      const [hour, minute, seconds] = time.split(':').map(Number)
      console.log(hour, minute, seconds)
      return hour * 3600 + minute * 60 + seconds
    },
    // 要提交的数据
    examRecordDatas() {
      // console.log(this.questionIds)
      const examName = this.paperInfo.title // 考卷名称
      const totalScore = this.paperInfo.score // 总分
      let userAnswer = [] // 用户答案ids
      let questionIds = [] // 考卷ids
      let scores = [] // 每题分数
      let errorQuestionIds = [] // 错题ids
      let errorAnswers = [] // 错题答案ids
      let userScore = 0 // 用户得分
      let lostScore = 0 // 失去的分数
      console.log(this.paperInfo, 'paperInfoTime')
      console.log(this.remainTime, 'remainTime')
      this.paperInfo.time = this.formatPaperInfoTime(this.paperInfo.time)
      // console.log(this.formatRemainTime(this.remainTime), 'remainTime')
      let duration = this.formatRemainTime(this.paperInfo.time - this.remainTime) // 时长
      console.log(duration, 'duration')
      // duration = duration.replace(/小时|分/g, ':').replace(/\s|秒/g, '') // 时长
      // duration = duration.split(':').map((item) => item.padStart(2, '0'))
      // const timeLength = duration.length
      // for (let i = 0; i < 3 - timeLength; i++) {
      //   duration.unshift('00')
      // }
      // duration = duration.join(':')
      console.log(this.questionIds, 'questionIds')

      for (const typeItem in this.questionIds) {
        // this.questionIds[typeItem].forEach((item) => {
        //   userAnswer.push(`${item.questionType}@${this.questionIds[typeItem].map((item) => item.answer).join('-')}`)
        // })
        console.log(this.questionIds[typeItem][0].questionTypeId, 'questionTypeId')
        // 用户答案ids
        userAnswer.push(
          `${typeItem === 'A3/4' ? 'A3_4' : this.questionIds[typeItem][0].questionTypeId}@${this.questionIds[typeItem]
            .map((item) => item.answer)
            .join('-')}`,
        )
        // 考卷ids
        questionIds.push(
          `${typeItem === 'A3/4' ? 'A3_4' : this.questionIds[typeItem][0].questionTypeId}@${this.questionIds[typeItem]
            .map((item) => item.id)
            .join(',')}`,
        )
        //#region
        // if (typeItem === 'B') {
        //   // const tempScores = []
        //   // for (const questionItem in this.questionIds[typeItem]) {
        //   //   this.questionIds[typeItem][questionItem].childList.map((item) => {
        //   //     tempScores.push(this.questionIds[typeItem][questionItem].score)
        //   //   })
        //   // }
        //   // scores.push('B@' + tempScores.join(','))
        //   // // 错题ids
        //   // const errorIdList = []
        //   // // 错题答案ids
        //   // const errorAnswerList = []
        //   // const nullIdList = this.questionIds[typeItem].filter((item) => item.correct === null)
        //   // // if (!lostScore) lostScore = 0
        //   // console.log(22222222222)
        //   // for (const nullIdListItem in nullIdList) {
        //   //   lostScore += nullIdList[nullIdListItem].childList.length * nullIdList[nullIdListItem].score
        //   //   errorIdList.push(...nullIdList[nullIdListItem].childList)
        //   //   errorAnswerList.push(...nullIdList[nullIdListItem].childList.map((item) => 'N'))
        //   // }
        //   // const wrongIdList = this.questionIds[typeItem]
        //   //   .filter((item) => item.correct !== null)
        //   //   .map((item) => {
        //   //     item.answer = item.answer.split(',')
        //   //     item.correct = item.correct.split(',')
        //   //     item.answer = item.answer.filter((idItem, idIndex) => item.correct[idIndex] === 'false')
        //   //     item.childList = item.childList.filter((idItem, idIndex) => item.correct[idIndex] === 'false')
        //   //     console.log(item.answer)
        //   //     return item
        //   //   })
        //   // for (const wrongIdListItem in wrongIdList) {
        //   //   lostScore += wrongIdList[wrongIdListItem].childList.length * wrongIdList[wrongIdListItem].score
        //   //   errorIdList.push(...wrongIdList[wrongIdListItem].childList)
        //   //   errorAnswerList.push(...wrongIdList[wrongIdListItem].answer)
        //   // }
        //   // errorQuestionIds.push(errorIdList.join(','))
        //   // errorAnswers.push(errorAnswerList.join('-'))
        // }
        //#endregion
        scores.push(
          `${typeItem === 'A3/4' ? 'A3_4' : this.questionIds[typeItem][0].questionTypeId}@${this.questionIds[typeItem]
            .map((item) => item.score)
            .join(',')}`,
        )
        errorQuestionIds.push(
          this.questionIds[typeItem]
            .filter((item) => !item.correct)
            .map((item) => item.id)
            .join(','),
        )
        errorAnswers.push(
          this.questionIds[typeItem]
            .filter((item) => !item.correct)
            .map((item) => item.answer)
            .join('-'),
        )
        lostScore = this.questionIds[typeItem]
          .filter((item) => !item.correct)
          .reduce((temp, now) => {
            return (temp += now.score)
          }, lostScore)
        // console.log(typeItem, this.questionTypes[typeItemIndex])
      }

      userAnswer = userAnswer.join('&')
      // console.log(userAnswer, 'join')
      questionIds = questionIds.join('&')
      errorQuestionIds = errorQuestionIds.join(',')
      errorAnswers = errorAnswers.join('-')
      userScore = this.paperInfo.score - lostScore
      this.userScore = userScore
      this.duration = duration
      scores = scores.join('&')
      console.log('设备id', sessionStorage.getItem('onlineEquipmentId'))
      console.log(userAnswer, 'userAnswer')
      console.log(scores, 'scores')
      console.log(questionIds, 'questionIds')
      const datas = {
        examName,
        totalScore,
        userAnswer,
        questionIds,
        errorQuestionIds,
        errorAnswers,
        userScore,
        duration,
        equipmentId: sessionStorage.getItem('onlineEquipmentId'),
        scores,
      }
      return datas
    },
    addExamRecord() {
      const data = this.examRecordDatas()
      data.examId = this.examId
      let obj = JSON.parse(sessionStorage.getItem('kaoshi'))

      console.log('这条考试的数据', obj)
      if (JSON.stringify(obj) !== '{}') {
        ;(data.examId = obj.examId), (data.totalScore = obj.totalScore)
      }
      console.log('提交的数据', data)

      insertExamRecord(data).then((res) => {
        console.log(res)
        this.dialogVisible = true
      })
    },
    backHome() {
      this.$router.replace({ path: '/onlineExam' })
      // let a = this.$router.resolve({
      //   name: 'OnlineExam'
      // })
      // console.log(a)
    },
  },
}
</script>

<style lang="scss" scoped>
.statusBox {
  margin-left: 20px;
}
.app-container {
  display: flex;
  height: 100vh;
  box-sizing: border-box;
  background-color: #fafafa;

  .actions {
    display: flex;
    width: 100%;
    justify-content: center;
    align-items: center;
    padding: 15px 10px;
  }
  // 信息板块
  .info-wrap {
    display: flex;
    width: 500px;

    box-sizing: border-box;
    scrollbar-width: none; /* Firefox */

    .info-container {
      width: inherit;
      padding-bottom: 20px;
      border-radius: 5px;
      background-color: #ffffff;

      // 试卷信息
      .paper-info {
        display: flex;
        justify-content: space-around;
        padding: 20px 15px 10px;
        border-bottom: 1px solid #f5f5f5;
        border-radius: 15px;
        background: #e5f5ff;
        box-shadow: 7px 7px 15px #bebebe, -7px -7px 15px #ffffff;
        margin-bottom: 20px;

        .paper-left {
          display: block;
        }
        .paper-right {
        }
        .paper-title {
          font-weight: 700;
        }
        .paper-declare {
          display: block;
          font-size: 14px;
          color: #606266;
          margin-top: 10px;
        }
      }
      // 答题卡
      .answer-sheet {
        height: calc(80vh - 40px);
        padding: 15px 5px 5px 20px;
        border-bottom: 1px solid #f5f5f5;
        overflow-y: auto;
        box-shadow: -4px 4px 15px 2px rgba(96, 95, 95, 0.32);
        background-color: rgba(150, 215, 255, 0.242);
        .question-type {
          .type-title {
            font-weight: 700;
            margin: 15px 0px;
          }

          .el-tag {
            width: 35px;
            text-align: center;
            margin: 0px 8px 8px 0px;
            padding: 0px;
            cursor: pointer;
          }
        }
      }
      // 剩余时间
      .time-remaining {
        padding: 10px;
        text-align: center;
        color: #606266;
        border-bottom: 1px solid #f5f5f5;
        .count-down {
          font-size: 20px;
          font-weight: 700;
          color: #f56c6c;
          margin-top: 5px;
        }
      }
      // 操作按钮
    }
  }

  // 试题板块
  .question-container {
    width: 1200px;
    height: 880px;
    margin-left: 50px;
    box-sizing: border-box;
    background-color: #ffffff;
    border-radius: 5px;
    box-shadow: rgba(0, 0, 0, 0.1) -4px 9px 25px -6px;
    background-color: rgba(150, 215, 255, 0.242);
    // 每一道题
    .questions {
      margin-left: 10px;
      min-height: 300px;
      height: 600px;
      max-height: 780px;
    }
    // 上/下一题
    .pre-next-btns {
      display: flex;
      // justify-content: flex-end;
      padding: 15px;
      margin-top: 100px;
      border-top: 1px dashed #c0c4cc;
    }
  }
}
</style>
